package userInterfaces;

import java.io.IOException;
import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.faces.bean.ManagedBean;

@ManagedBean(name="loginBean")
@ViewScoped
public class LoginManagedBean2 implements Serializable {
	@ManagedProperty(value = "#{userSession}")
	
	private UserSessionManagedBean userSession;
	public UserSessionManagedBean getUserSession() {
		return userSession;
	}

	public void setUserSession(UserSessionManagedBean userSession) {
		this.userSession = userSession;
	}

	public String getOriginalURL() {
		return originalURL;
	}

	public void setOriginalURL(String originalURL) {
		this.originalURL = originalURL;
	}
	private String originalURL;
	private String username;
	private String password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@PostConstruct
	public void init() {
		System.err.println(" inizializzo loginbean");

		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		HttpServletRequest requesttt = (HttpServletRequest) externalContext.getRequest();
		System.err.println("init eccolo: "+userSession.getOriginalURL());
		String forwardedRequestURI = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);
		if ((this.originalURL = requesttt.getParameter("originalURL")) != null) {
			System.err.println(" If the user was redirected, retrieve the originalURL from the request's \"originalURL\" parameter");
			return;
		} else if (forwardedRequestURI == null) {
			System.err.println(" caso in cui accedo a funzione protetta, glassfish fa un forward non convenzionale");
//			System.err.println(" If the user logged in directly from the top bar, simply redirect to the originalURL recorded by UserSessionBean");
			this.originalURL = userSession.getOriginalURL();
			System.err.println("originalurl preso da usersession "+originalURL);

			if (originalURL == null) {
				System.err.println(" Redirect to home page in case the user didn't surf any pages before logging in");
				this.originalURL = requesttt.getContextPath() + "/home.xhtml";
			}
		} else {
			System.err.println(" caso in cui tento di accedere a pagina protetta, glassfish fa un forward standard");
//			System.err.println(" If the user was forwarded to the login page, re-build the orignal requestURL");
			this.originalURL = forwardedRequestURI;
			System.err.println("original url preso da forwarderequesturi "+originalURL);
			String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

			if (originalQuery != null) {
				this.originalURL += "?" + originalQuery;
			}
		}
	}
	public void login() {
		FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();
        HttpServletRequest richiesta = (HttpServletRequest) externalContext.getRequest();
		
        System.err.println(" Perform login logic");
		try {
			richiesta.login(username, password);
			try {
				System.err.println(" Redirect the user after successful login to: "+originalURL);
				FacesContext.getCurrentInstance().getExternalContext().redirect(originalURL);
			} catch (IOException ex) {
			System.out.println("UserSessionBean - Exception: " + ex.toString());
			}
		} catch (ServletException e) {
			  System.err.println("errore login");
	          context.addMessage(null, new FacesMessage("login Error"));
//	          try {
//				FacesContext.getCurrentInstance().getExternalContext().redirect("loginError.xhtml");
//			} catch (IOException e1) {
//				// TODO Auto-generated catch block
//				e1.printStackTrace();
//			}
		} 
		
	}
}
